package com.wang.web3;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.wang.web3.adapter.KittyGrilAdapter;
import com.wang.web3.base.Constant;
import com.wang.web3.bean.ContractBean;
import com.wang.web3.bean.GirlBean;
import com.wang.web3.bean.TianWallet;
import com.wang.web3.contracts.GirlCore;
import com.wang.web3.data.service.ICallBackListener;
import com.wang.web3.data.service.impl.ApiServiceImpl;
import com.wang.web3.utils.SPUtils;

import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.Web3jFactory;
import org.web3j.protocol.core.RemoteCall;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import org.web3j.tuples.generated.Tuple6;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.functions.Action1;

public class GirlBreakDownActivity extends AppCompatActivity implements KittyGrilAdapter.PersonHolderListener, View.OnClickListener {

    RecyclerView mRv;
    ImageView iv1;
    Button mBtnStart;
    Gson gson = new Gson();
    List<GirlBean.DataBean> dataBeans;
    KittyGrilAdapter kittyGrilAdapter;
    GirlCore girlCore;

    int girl1 = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_girl_breakdown);
        mRv = findViewById(R.id.mRv);
        iv1 = findViewById(R.id.mGirl1);
        mBtnStart = findViewById(R.id.mBtnStart);
        findViewById(R.id.mLeftIv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mBtnStart.setOnClickListener(this);
        init();
        initData();

    }

    private void initData() {
        String lockWallet = (String) SPUtils.get(this, Constant.WALLETLOCKADDRESS, "");
        if (lockWallet.equals("")) {
            return;
        }
        TianWallet tianWallet = gson.fromJson(lockWallet, TianWallet.class);
        ApiServiceImpl.getInstence().myGirlList(tianWallet.getAdress(), new ICallBackListener() {
            @Override
            public void onSuccess(String string) {
                GirlBean girlBean = gson.fromJson(string, GirlBean.class);
                dataBeans.addAll(girlBean.getData());
                kittyGrilAdapter.notifyDataSetChanged();
                getGirl();

            }

            @Override
            public void onFaild(String string) {

            }
        });
    }

    private void getGirl() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < dataBeans.size(); i++) {
                    try {
                        Observable<Tuple6<BigInteger, BigInteger, BigInteger, BigInteger, Boolean, BigInteger>> observable = girlCore.getGirl(new BigInteger(dataBeans.get(i).getId() + "")).observable();
                        final int finalI = i;
                        observable.subscribe(new Action1<Tuple6<BigInteger, BigInteger, BigInteger, BigInteger, Boolean, BigInteger>>() {
                            @Override
                            public void call(Tuple6<BigInteger, BigInteger, BigInteger, BigInteger, Boolean, BigInteger> tuple6) {
                                Log.e("tag", tuple6.toString());
                                if (tuple6.getValue3().equals(new BigInteger("0"))) {
                                    dataBeans.get(finalI).setDisabled(true);
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                Message message = Message.obtain();
                message.what = 1;
                handler.sendMessage(message);
            }
        }).start();
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 1) {
                kittyGrilAdapter.notifyDataSetChanged();
            } else if (msg.what == 2) {
                Toast.makeText(GirlBreakDownActivity.this, "分解成功", Toast.LENGTH_SHORT).show();
                finish();
            }
            return false;
        }
    });

    private void init() {

        Web3j web3 = Web3jFactory.build(new HttpService(Constant.URL));
        String wallet = (String) SPUtils.get(this, Constant.WALLETLOCKADDRESS, "");
        String contract = (String) SPUtils.get(this, Constant.CONTRACTADDRESS, "");
        TianWallet tianWallet = gson.fromJson(wallet, TianWallet.class);
        ContractBean contractBean = gson.fromJson(contract, ContractBean.class);
        Credentials credentials = Credentials.create(tianWallet.getPrivateKey().substring(2));
        if (contractBean != null && contractBean.getMagicKeys() != null) {
            girlCore = GirlCore.load(contractBean.getGirlCore(), web3, credentials, Constant.GAS_PRICE, Constant.GAS_LIMIT);
        }

        dataBeans = new ArrayList<>();
        kittyGrilAdapter = new KittyGrilAdapter(dataBeans, this);
        mRv.setLayoutManager(new GridLayoutManager(this, 2));
        mRv.setAdapter(kittyGrilAdapter);
    }

    @Override
    public void onGirlPersonItemClicked(View v, MotionEvent event, int position) {
        if (!dataBeans.get(position).isDisabled()) {
            return;
        }

        if (girl1 != 0) {
            return;
        } else {
            girl1 = dataBeans.get(position).getId();
            Glide.with(this).load(dataBeans.get(position).getPicBody()).into(iv1);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mBtnStart:
                if (girl1 == 0) {
                    Toast.makeText(this, "请选择！！！！", Toast.LENGTH_SHORT).show();
                    return;
                }
                Toast.makeText(this, "正在分解请稍等", Toast.LENGTH_SHORT).show();
                final RemoteCall<TransactionReceipt> tp = girlCore.decomposition(new BigInteger(girl1 + ""));
                girl1 = 0;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        tp.observable().subscribe(new Action1<TransactionReceipt>() {
                            @Override
                            public void call(TransactionReceipt transactionReceipt) {
                                Message message = Message.obtain();
                                message.what = 2;
                                handler.sendMessage(message);
                            }
                        });
                    }
                }).start();
                break;
        }
    }
}
